﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;

public partial class XSocketClient
{

    public void Connect(string ip, int port)
    {
        NetWorkChanged(NetWorkState.Connecting);
        _socket = GenerateSocket();

        //开始计时 超时
        StopCoWaitConnect();
        _coTimeout = StartCoroutine(CoWaitConnect());

        _socket.BeginConnect(ip, port, OnConnect, _socket);
    }

    private void OnConnect(IAsyncResult ar)
    {
        try
        {
            _socket.EndConnect(ar);
            NetWorkChanged(NetWorkState.Connected);
        }
        catch (SocketException se)
        {
            NetWorkChanged(NetWorkState.SocketError, se.Message);
        }
        catch (Exception e)
        {
            NetWorkChanged(NetWorkState.Error, e.Message);
        }
    }


    private IEnumerator CoWaitConnect()
    {
        yield return new WaitForSeconds(timeout);
        NetWorkChanged(NetWorkState.Timeout, "超时链接:" + timeout + "秒");
        _coTimeout = null;
        throw new Exception("还没实现断开socket");
    }

    private void StopCoWaitConnect()
    {
        if (_coTimeout != null)
        {
            StopCoroutine(_coTimeout);
            _coTimeout = null;
        }
    }

}
